package com.zmn.oms.business.impl.base;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.engineer.common.constants.DubboConsts;
import com.zmn.base.engineer.common.enums.SupervisorIdentityTypeEnum;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerListRemoteService;
import com.zmn.base.engineer.dubbo.interfaces.supervisor.EngineerSupervisorListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.mcc.common.constant.DpermitConsts;
import com.zmn.mcc.common.dto.organize.OrganizeDRO;
import com.zmn.mcc.common.dto.permit.DpermitLitDO;
import com.zmn.mcc.common.dto.permit.SpermitDTO;
import com.zmn.mcc.dubbo.interfaces.organize.OrganizeListRemoteService;
import com.zmn.mcc.dubbo.interfaces.staff.StaffPermitRemoteService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDistributeConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.work.EsConcatPhoneQueryBO;
import com.zmn.oms.model.bo.work.EsQueryBuilder;
import com.zmn.oms.model.entity.part.OrderPartEsQuery;
import com.zmn.oms.model.entity.work.OrderBaseEsQuery;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.entity.work.list.OrderWorkBCustomerQuery;
import com.zmn.oms.model.entity.work.list.OrderWorkChannelQuery;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import com.zmn.uuc.common.dro.user.UserBaseDRO;
import com.zmn.uuc.dubbo.interfaces.user.UserListRemoteService;
import jodd.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SourceFilter;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @author lujia
 * @date 2018/12/28 19:39
 */
public abstract class AbstractListEsQueryServiceImpl {
    @DubboReference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    protected StaffPermitRemoteService staffPermitRemoteService;
    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerSupervisorListRemoteService engineerSupervisorListRemoteService;
    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerListRemoteService engineerListRemoteService;
    @DubboReference(version = com.zmn.mcc.dubbo.dto.DubboConsts.INTERFACE_VERSION, check = false)
    protected OrganizeListRemoteService organizeListRemoteService;
    @DubboReference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    UserListRemoteService userListRemoteService;
    @Resource
    private OrderEncryptService orderEncryptService;

    private Logger logger = LoggerFactory.getLogger(AbstractListEsQueryServiceImpl.class);

    /**
     * 构建 search query
     *
     * @param query 查询条件
     * @return search query
     */
    protected NativeSearchQuery builderSearchQuery(OrderBaseEsQuery query) {

        if (logger.isDebugEnabled()) {
            logger.debug("OrderEsQuery：{}", JSON.toJSONString(query));
        }

        BoolQueryBuilder queryBuilder = null;
        try {

            // 手机号码特殊处理
            EsConcatPhoneQueryBO concatPhoneQueryByOrderBaseEsQuery = this.getConcatPhoneQueryByOrderBaseEsQuery(query);

            // 拼装查询条件
            queryBuilder = EsQueryBuilder.getQuery(query);

            if (Objects.equals(query.getPermit(), com.zmn.consts.GlobalConsts.YES)) {
                // 数据权限
                appendPermitData(query, queryBuilder);
            }

            // 用户手机号查询
            appendConcatPhoneQuery(queryBuilder, concatPhoneQueryByOrderBaseEsQuery);

            // 待派单 查询
            appendDistribute(queryBuilder, query);

            // 责任工程师 查询
            appendLiableMaster(queryBuilder, query);

            // 子公司 or 服务商 查询
            appendCompanyOrSp(queryBuilder, query);

            // 保修卡 查询
            appendWarrantyCodesQuery(queryBuilder, query);

            logger.info("Order es query builder:{}", queryBuilder.toString());

        } catch (IllegalAccessException e) {
            logger.error("get query fail", e);
            return null;
        } catch (OmsBaseException e) {
//            logger.error("get query fail", e);
            return null;
        } catch (Exception e) {
            logger.error("get query fail", e);
            return null;
        }

        NativeSearchQuery searchQuery = new NativeSearchQuery(queryBuilder);
        if (Objects.equals(query.getOrderField(), "provinceCityName")) {
            searchQuery.setPageable(EsQueryBuilder.getPageRequestByProvinceCityName(query));
        } else {
            searchQuery.setPageable(EsQueryBuilder.getPageRequest(query));
        }
        List<String> includesList = query.getIncludes();
        List<String> excludesList = query.getExcludes();
        String[] includes = {};
        String[] excludes = {};

        if (includesList != null) {
            includes = includesList.toArray(new String[includesList.size()]);
        }

        if (excludesList != null) {
            excludes = excludesList.toArray(new String[excludesList.size()]);
        }

        if (includes.length > 0 || excludes.length > 0) {
            SourceFilter sourceFilter = new FetchSourceFilter(includes, excludes);
            searchQuery.addSourceFilter(sourceFilter);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("queryBuilder={}", queryBuilder.toString());
        }

        return searchQuery;
    }

    /**
     * 获取手机号查询数据
     *
     * @param query
     * @return
     */
    private EsConcatPhoneQueryBO getConcatPhoneQueryByOrderBaseEsQuery(OrderBaseEsQuery query) {

        // 手机号
        List<String> phoneList = Lists.newArrayListWithExpectedSize(10);
        List<String> phoneEnd4List = Lists.newArrayListWithExpectedSize(10);
        List<Long> userIdList = null;

        if (query instanceof OrderWorkQuery) {
            // 工单查询
            OrderWorkQuery orderWorkQuery = (OrderWorkQuery) query;

            // 单个手机号查询
            if (StringUtils.isNotBlank(orderWorkQuery.getConcatPhone())) {
                if (orderWorkQuery.getConcatPhone().length() == 4) {
                    phoneEnd4List.add(orderWorkQuery.getConcatPhone());
                } else {
                    phoneList.add(orderWorkQuery.getConcatPhone());
                }
            }

            // 多个手机号查询
            if (CollectionUtils.isNotEmpty(orderWorkQuery.getConcatPhoneList())) {
                orderWorkQuery.getConcatPhoneList().forEach(item -> {
                    if (StringUtils.isBlank(item)) {
                        return;
                    }
                    if (item.length() == 4) {
                        phoneEnd4List.add(item);
                    } else {
                        phoneList.add(item);
                    }
                });
            }

            // 加密手机号查询
            if (StringUtils.isNotBlank(orderWorkQuery.getCryptoPhone())) {
                // 解密处理
                phoneList.add(orderEncryptService.decrypt(orderWorkQuery.getCryptoPhone()));
            }

            // 手机号对应的用户ID
            boolean queryUserIds = Objects.equals(orderWorkQuery.getQueryConcatPhoneUsers(), true) &&
                    StringUtils.isNotBlank(orderWorkQuery.getConcatPhone()) &&
                    orderWorkQuery.getConcatPhone().length() > 5;
            if (queryUserIds) {
                try {
                    // 根据下单用户电话查询用户id，再根据用户id查询工单
                    ResponseDTO<List<UserBaseDRO>> listResponseDTO = userListRemoteService.listUserByMobile(orderWorkQuery.getConcatPhone(), false);
                    logger.debug("es#query#userListRemoteService#listUserByMobil【{}】", listResponseDTO);
                    List<UserBaseDRO> userBaseDROList = listResponseDTO.getData();
                    if (CollectionUtils.isNotEmpty(userBaseDROList)) {
                        userIdList = userBaseDROList.stream().map(UserBaseDRO::getUserId)
                                .distinct().collect(Collectors.toList());
                    }
                } catch (Exception ex) {
                }
            }
        } else if (query instanceof OrderWorkChannelQuery) {
            // 渠道查询
            OrderWorkChannelQuery orderWorkChannelQuery = (OrderWorkChannelQuery) query;
            if (StringUtils.isNotBlank(orderWorkChannelQuery.getTelephone())) {
                if (orderWorkChannelQuery.getTelephone().length() == 4) {
                    phoneEnd4List.add(orderWorkChannelQuery.getTelephone());
                } else {
                    phoneList.add(orderWorkChannelQuery.getTelephone());
                }
            }
        } else if (query instanceof OrderWorkBCustomerQuery) {
            // 渠道查询
            OrderWorkBCustomerQuery orderWorkBCustomerQuery = (OrderWorkBCustomerQuery) query;
            if (StringUtils.isNotBlank(orderWorkBCustomerQuery.getTelephone())) {
                if (orderWorkBCustomerQuery.getTelephone().length() == 4) {
                    phoneEnd4List.add(orderWorkBCustomerQuery.getTelephone());
                } else {
                    phoneList.add(orderWorkBCustomerQuery.getTelephone());
                }
            }
        }

        EsConcatPhoneQueryBO esConcatPhoneQueryBO = new EsConcatPhoneQueryBO();
        esConcatPhoneQueryBO.setPhoneList(phoneList);
        esConcatPhoneQueryBO.setPhoneEnd4List(phoneEnd4List);
        esConcatPhoneQueryBO.setUserIdList(userIdList);
        return esConcatPhoneQueryBO;
    }

    /**
     * 保修卡查询处理
     *
     * @param queryBuilder
     * @param orderBaseEsQuery
     */
    void appendWarrantyCodesQuery(BoolQueryBuilder queryBuilder, OrderBaseEsQuery orderBaseEsQuery) {

        if (!(orderBaseEsQuery instanceof OrderWorkQuery)) {
            return;
        }

        OrderWorkQuery orderWorkQuery = (OrderWorkQuery) orderBaseEsQuery;
        String warrantyCode = orderWorkQuery.getWarrantyCode();
        List<String> warrantyCodes = orderWorkQuery.getWarrantyCodes();
        if (StringUtil.isBlank(warrantyCode) && CollectionUtil.isNullOrEmpty(warrantyCodes)) {
            return;
        }

        List<QueryBuilder> must = queryBuilder.filter();
        logger.info("#appendWarrantyCodesQuery# warrantyCode:{}, warrantyCodes:{}", warrantyCode, warrantyCodes);

        // 保修卡号列表查询
        if(StringUtil.isBlank(warrantyCode)) {

            // 保修卡号列表
            BoolQueryBuilder wcBuilder = QueryBuilders.boolQuery();
            wcBuilder.must(QueryBuilders.termsQuery("warrantyCodes.keyword", warrantyCodes));

            must.add(wcBuilder);
            return;
        }

        if (CollectionUtil.isNullOrEmpty(warrantyCodes)) {
            warrantyCodes = Lists.newArrayList(warrantyCode);
        }

        BoolQueryBuilder wcBuilder = QueryBuilders.boolQuery();
        wcBuilder.should(QueryBuilders.termsQuery("warrantyCodes.keyword", warrantyCodes));
        wcBuilder.should(QueryBuilders.termQuery("warrantyCode", warrantyCode));
        wcBuilder.must(QueryBuilders.termQuery("hasWarrantyCode", Boolean.TRUE));
        wcBuilder.minimumShouldMatch(1);

        must.add(wcBuilder);
    }

    /**
     * 手机号查询处理
     *
     * @param queryBuilder
     * @param concatPhoneQuery
     */
    void appendConcatPhoneQuery(BoolQueryBuilder queryBuilder, EsConcatPhoneQueryBO concatPhoneQuery) {
        if (concatPhoneQuery == null) {
            return;
        }

        List<QueryBuilder> must = queryBuilder.filter();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 手机号后4位查询
        if (CollectionUtils.isNotEmpty(concatPhoneQuery.getPhoneEnd4List())) {
            boolQueryBuilder.should(QueryBuilders.termsQuery("contact.phoneEnd4", concatPhoneQuery.getPhoneEnd4List()));
        }
        // 加密手机号查询
        if (CollectionUtils.isNotEmpty(concatPhoneQuery.getPhoneList())) {
            boolQueryBuilder.should(QueryBuilders.termsQuery("contact.phone", orderEncryptService.encrypt(concatPhoneQuery.getPhoneList())));
        }

        // 手机号对应的用户ID
        if (CollectionUtils.isNotEmpty(concatPhoneQuery.getUserIdList())) {
            boolQueryBuilder.should(QueryBuilders.termsQuery("userId", concatPhoneQuery.getUserIdList()));
        }

        must.add(boolQueryBuilder);
    }

    /**
     * 待派单查询
     * @param queryBuilder
     * @param orderBaseEsQuery
     */
    void appendDistribute(BoolQueryBuilder queryBuilder, OrderBaseEsQuery orderBaseEsQuery) {
        if (!(orderBaseEsQuery instanceof OrderWorkQuery)) {
            return;
        }
        OrderWorkQuery orderWorkQuery = (OrderWorkQuery) orderBaseEsQuery;
        if (!Objects.equals(orderWorkQuery.getIsWaitDistribute(), true)) {
            return;
        }

        List<QueryBuilder> must = queryBuilder.filter();
        // 服务商待派单
        BoolQueryBuilder spBuilder = QueryBuilders.boolQuery();
        spBuilder.must(QueryBuilders.termQuery("status", OrderStatusConsts.WORK_STATUS_ASSIGN));
        spBuilder.must(QueryBuilders.termQuery("distributeWay", OrderDistributeConsts.DISTRIBUTE_WAY_SP));
        BoolQueryBuilder platBuilder = QueryBuilders.boolQuery();
        // 平台直派待派单
        platBuilder.must(QueryBuilders.termQuery("status", OrderStatusConsts.WORK_STATUS_CONFIRM));
        platBuilder.must(QueryBuilders.termQuery("distributeWay", OrderDistributeConsts.DISTRIBUTE_WAY_PLAT));
        // should组合
        BoolQueryBuilder waitDistributeBuilder = QueryBuilders.boolQuery();
        waitDistributeBuilder.should(spBuilder);
        waitDistributeBuilder.should(platBuilder);

        must.add(waitDistributeBuilder);
    }

    /**
     * 责任工程师查询处理
     * @param queryBuilder
     * @param orderBaseEsQuery
     */
    void appendLiableMaster(BoolQueryBuilder queryBuilder, OrderBaseEsQuery orderBaseEsQuery) {
        if (!(orderBaseEsQuery instanceof OrderWorkQuery)) {
            return;
        }
        OrderWorkQuery orderWorkQuery = (OrderWorkQuery) orderBaseEsQuery;
        if (NumberUtil.isNullOrZero(orderWorkQuery.getCancelLiableMasterId())) {
            return;
        }

        // 兼容历史数据，没有同步责任工程师
        List<QueryBuilder> must = queryBuilder.filter();
        BoolQueryBuilder masterBuilder = QueryBuilders.boolQuery();
        masterBuilder.mustNot(QueryBuilders.existsQuery("cancelLiableMasterId"));
        masterBuilder.must(QueryBuilders.termQuery("masterId", orderWorkQuery.getCancelLiableMasterId()));

        // 有责任工程师的，需要查询责任工程师字段
        BoolQueryBuilder liableMasterBuilder = QueryBuilders.boolQuery();
        liableMasterBuilder.must(QueryBuilders.termQuery("cancelLiableMasterId", orderWorkQuery.getCancelLiableMasterId()));

        // should组合
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(masterBuilder);
        boolQueryBuilder.should(liableMasterBuilder);

        // 查询责任工程师必须是新单or返修单
        must.add(QueryBuilders.termsQuery("type", Arrays.asList(OrderConsts.ORDER_TYPE_NEW, OrderConsts.ORDER_TYPE_REWORK)));
        must.add(boolQueryBuilder);
    }

    /**
     * 子公司、服务商查询处理
     * @param queryBuilder
     * @param orderBaseEsQuery
     */
    void appendCompanyOrSp(BoolQueryBuilder queryBuilder, OrderBaseEsQuery orderBaseEsQuery) {
        if (!(orderBaseEsQuery instanceof OrderWorkQuery)) {
            return;
        }
        OrderWorkQuery orderWorkQuery = (OrderWorkQuery) orderBaseEsQuery;

        // 子公司
        if (CollectionUtils.isNotEmpty(orderWorkQuery.getCompanyIdOrGridCompanyIdList())) {
            // 子公司查询
            List<QueryBuilder> must = queryBuilder.filter();
            BoolQueryBuilder companyBuilder = QueryBuilders.boolQuery();
            companyBuilder.must(QueryBuilders.termsQuery("companyId", orderWorkQuery.getCompanyIdOrGridCompanyIdList()));

            // 行政子公司查询
            BoolQueryBuilder gridCompanyBuilder = QueryBuilders.boolQuery();
            gridCompanyBuilder.must(QueryBuilders.termQuery("companyId", 0));
            gridCompanyBuilder.must(QueryBuilders.termsQuery("gridCompanyId", orderWorkQuery.getCompanyIdOrGridCompanyIdList()));

            // should组合
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.should(companyBuilder);
            boolQueryBuilder.should(gridCompanyBuilder);

            must.add(boolQueryBuilder);
        }

        // 服务商
        if (NumberUtil.isNotNullOrZero(orderWorkQuery.getManageCompanyIdOrGridManageCompanyId())) {
            // 服务商查询
            List<QueryBuilder> must = queryBuilder.filter();
            BoolQueryBuilder manageCompanyBuilder = QueryBuilders.boolQuery();
            manageCompanyBuilder.must(QueryBuilders.termQuery("manageCompanyId", orderWorkQuery.getManageCompanyIdOrGridManageCompanyId()));

            // 行政服务商查询
            BoolQueryBuilder gridManageCompanyBuilder = QueryBuilders.boolQuery();
            gridManageCompanyBuilder.must(QueryBuilders.termQuery("manageCompanyId", 0));
            gridManageCompanyBuilder.must(QueryBuilders.termQuery("gridManageCompanyId", orderWorkQuery.getManageCompanyIdOrGridManageCompanyId()));

            // should组合
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.should(manageCompanyBuilder);
            boolQueryBuilder.should(gridManageCompanyBuilder);

            must.add(boolQueryBuilder);
        }

        // 服务商
        if (CollectionUtils.isNotEmpty(orderWorkQuery.getManageCompanyIdOrGridManageCompanyIdList())) {

            Integer[] manageCompanyIdList = orderWorkQuery.getManageCompanyIdOrGridManageCompanyIdList().toArray(new Integer[orderWorkQuery.getManageCompanyIdOrGridManageCompanyIdList().size()]);

            // 服务商查询
            List<QueryBuilder> must = queryBuilder.filter();
            BoolQueryBuilder manageCompanyBuilder = QueryBuilders.boolQuery();
            manageCompanyBuilder.must(QueryBuilders.termsQuery("manageCompanyId", manageCompanyIdList));

            // 行政服务商查询
            BoolQueryBuilder gridManageCompanyBuilder = QueryBuilders.boolQuery();
            gridManageCompanyBuilder.must(QueryBuilders.termQuery("manageCompanyId", 0));
            gridManageCompanyBuilder.must(QueryBuilders.termsQuery("gridManageCompanyId", manageCompanyIdList));

            // should组合
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.should(manageCompanyBuilder);
            boolQueryBuilder.should(gridManageCompanyBuilder);

            must.add(boolQueryBuilder);
        }
    }

    /**
     * 服务商查询处理
     * @param queryBuilder
     * @param orderBaseEsQuery
     */
    void appendManageCompany(BoolQueryBuilder queryBuilder, OrderBaseEsQuery orderBaseEsQuery) {
        if (!(orderBaseEsQuery instanceof OrderWorkQuery)) {
            return;
        }
        OrderWorkQuery orderWorkQuery = (OrderWorkQuery) orderBaseEsQuery;
        if (CollectionUtils.isEmpty(orderWorkQuery.getCompanyIdOrGridCompanyIdList())) {
            return;
        }

        // 公司查询
        List<QueryBuilder> must = queryBuilder.filter();
        BoolQueryBuilder companyBuilder = QueryBuilders.boolQuery();
        companyBuilder.must(QueryBuilders.termsQuery("companyId", orderWorkQuery.getCompanyIdOrGridCompanyIdList()));

        // 行政公司查询
        BoolQueryBuilder gridCompanyBuilder = QueryBuilders.boolQuery();
        gridCompanyBuilder.must(QueryBuilders.termQuery("companyId", 0));
        gridCompanyBuilder.must(QueryBuilders.termsQuery("gridCompanyId", orderWorkQuery.getCompanyIdOrGridCompanyIdList()));

        // should组合
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(companyBuilder);
        boolQueryBuilder.should(gridCompanyBuilder);

        must.add(boolQueryBuilder);
    }

    /**
     * 添加数据权限
     *
     * @param query
     * @param queryBuilder
     */
    void appendPermitData(OrderBaseEsQuery query, BoolQueryBuilder queryBuilder) throws OmsBaseException {
        boolean isPartQuery = query instanceof OrderPartEsQuery;// 是否配件查询

        Integer staffId = query.getStaffId();
        if (staffId == null) {
            return;
        }

        List<QueryBuilder> must = queryBuilder.filter();

        // 工程师主管查询
        if (NumberUtil.isNotNullOrZero(staffId) && !isPartQuery) {
            logger.info("appendPermitData#getIdByIdentityTypeAndObjectId 入参 [{}]", staffId);
            ResponseDTO<Integer> engineerOrSupervisorByStaffIdRsp = engineerSupervisorListRemoteService.
                    getIdByIdentityTypeAndObjectId(SupervisorIdentityTypeEnum.SUPERVISOR_IDENTITY_TYPE_ENUM_STAFF.getCode(), staffId);
            logger.info("appendPermitData#getIdByIdentityTypeAndObjectId 出参 [{}]", JSON.toJSONString(engineerOrSupervisorByStaffIdRsp));
            Integer engineerOrSupervisorId = engineerOrSupervisorByStaffIdRsp.getData();

//            logger.info("appendPermitData#getByStaffId 入参 [{}]", staffId);
//            ResponseDTO<SupervisorDetailDRO> engineerOrSupervisorByStaffIdRsp = engineerSupervisorListRemoteService.getByStaffId(staffId);
//            logger.info("appendPermitData#getByStaffId 出参 [{}]", JSON.toJSONString(engineerOrSupervisorByStaffIdRsp));
//            SupervisorDetailDRO engineerOrSupervisorDRO = engineerOrSupervisorByStaffIdRsp.getData();
//            if (Objects.nonNull(engineerOrSupervisorDRO)) {
//                must.add(QueryBuilders.termQuery("masterSupervisorId", engineerOrSupervisorDRO.getSupervisorId()));
            if (Objects.nonNull(engineerOrSupervisorId)) {
                must.add(QueryBuilders.termQuery("masterSupervisorId", engineerOrSupervisorId));

                /*// 主管管理的工程师
                ResponseDTO<List<Integer>> listEngineerIdsResponseDTO = supervisorListRemoteService.listEngineerIdsBySupId(engineerOrSupervisorDRO.getMasterId());
                if (CollectionUtils.isNotEmpty(listEngineerIdsResponseDTO.getData())) {
                    must.add(QueryBuilders.termsQuery("masterId", listEngineerIdsResponseDTO.getData()));
                }

                // 主管管理的业务类型和产品分组
                ResponseDTO<List<SupervisorProductDRO>> supervisorProductResponseDTO = supervisorListRemoteService.listSupervisorProductById(engineerOrSupervisorDRO.getMasterId());
                List<SupervisorProductDRO> supervisorProductDROS = supervisorProductResponseDTO.getData();
                if (CollectionUtils.isNotEmpty(supervisorProductDROS)) {
                    List<Integer> bizList = supervisorProductDROS.stream().filter(item -> NumberUtil.isNotNullOrZero(item.getBizType()))
                            .map(SupervisorProductDRO::getBizType).distinct().collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(bizList)) {
                        must.add(QueryBuilders.termsQuery("bizType", bizList));
                    }
                    List<Integer> productGroupList = supervisorProductDROS.stream().filter(item -> NumberUtil.isNotNullOrZero(item.getProductGroupId())).
                            map(SupervisorProductDRO::getProductGroupId).distinct().collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(productGroupList)) {
                        must.add(QueryBuilders.termsQuery("servProductGroupId", productGroupList));
                    }
                }*/
            }
        }

        // 公司权限
        boolean permitOrganize = Objects.equals(query.getPermitOrganize(), com.zmn.consts.GlobalConsts.YES);
        if (permitOrganize) {
            SpermitDTO<Integer> orgSpermitDTO = staffPermitRemoteService.listDpermitByStaffId(staffId, DpermitConsts.TYPE_ORGANIZE, true);
            if (CollectionUtils.isNotEmpty(orgSpermitDTO.getItems())) {

                // 执行公司权限
                BoolQueryBuilder manageBoolQueryBuilder = QueryBuilders.boolQuery();
                // 行政公司权限
                BoolQueryBuilder gridBoolQueryBuilder = QueryBuilders.boolQuery();
                // 按照组织架构查询
                List<Integer> level1;
                if (Objects.equals(orgSpermitDTO.getLevel(), com.zmn.consts.GlobalConsts.LEVEL_1)) {
                    level1 = orgSpermitDTO.getItems();
                } else {
                    SpermitDTO<Integer> platSpermitDTO = staffPermitRemoteService.listDpermitByStaffId(staffId, DpermitConsts.TYPE_ORGANIZE_PLAT, false);
                    level1 = platSpermitDTO.getItems();
                }

                // 总公司，可以查询未分单的数据
                if (Objects.nonNull(query.getOrgId())) {
                    ResponseDTO<OrganizeDRO> organDROResponseDTO = organizeListRemoteService.getByKey(query.getOrgId());
                    OrganizeDRO organDRO = organDROResponseDTO.getData();
                    if (Objects.nonNull(level1) && Objects.nonNull(organDRO) && Objects.nonNull(organDRO.getLevel()) && organDRO.getLevel() <= com.zmn.consts.GlobalConsts.LEVEL_2) {
                        level1.add(com.zmn.consts.GlobalConsts.NONE);
                    }
                }
                if (CollectionUtils.isNotEmpty(level1)) {
                    manageBoolQueryBuilder.must(QueryBuilders.termsQuery("orgOneId", level1));
                }
                // 2级行政公司
                if (Objects.equals(orgSpermitDTO.getLevel(), com.zmn.consts.GlobalConsts.LEVEL_2)) {
                    manageBoolQueryBuilder.must(QueryBuilders.termsQuery("orgTwoId", orgSpermitDTO.getItems()));
                }
                // 3级行政公司
                if (Objects.equals(orgSpermitDTO.getLevel(), com.zmn.consts.GlobalConsts.LEVEL_3)) {
                    manageBoolQueryBuilder.must(QueryBuilders.termsQuery("orgThreeId", orgSpermitDTO.getItems()));
                }

                // 1级不处理，2级、3级 需要根据子公司查询
                if (Objects.equals(orgSpermitDTO.getLevel(), com.zmn.consts.GlobalConsts.LEVEL_2) || Objects.equals(orgSpermitDTO.getLevel(), com.zmn.consts.GlobalConsts.LEVEL_3)) {

                    // 查询全部子公司
                    SpermitDTO<Integer> subOrgSpermitDTO = staffPermitRemoteService.listDpermitByStaffId(staffId, DpermitConsts.TYPE_ORGANIZE_SUB, true);

                    if (CollectionUtils.isNotEmpty(subOrgSpermitDTO.getItems())) {
                        // 转化为公司，查询行政公司
                        ResponseDTO<List<OrganizeDRO>> listResponseDTO = organizeListRemoteService.listByOrgIds(subOrgSpermitDTO.getItems(), com.zmn.consts.GlobalConsts.YES);
                        if (CollectionUtils.isNotEmpty(listResponseDTO.getData())) {
                            List<Integer> collect = listResponseDTO.getData().stream().filter(item -> Objects.nonNull(item.getCompanyId()))
                                    .map(OrganizeDRO::getCompanyId).collect(Collectors.toList());
                            gridBoolQueryBuilder.must(QueryBuilders.termsQuery("gridCompanyId", collect));
                        }
                    }
                }

                // 4级
                if (Objects.equals(orgSpermitDTO.getLevel(), com.zmn.consts.GlobalConsts.LEVEL_4)) {
                    manageBoolQueryBuilder.must(QueryBuilders.termsQuery("manageCompanyId", orgSpermitDTO.getItems()));
                    gridBoolQueryBuilder.must(QueryBuilders.termsQuery("gridManageCompanyId", orgSpermitDTO.getItems()));
                }

                if (CollectionUtil.isNotNullOrEmpty(gridBoolQueryBuilder.must())) {
                    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                    boolQueryBuilder.should(manageBoolQueryBuilder);
                    boolQueryBuilder.should(gridBoolQueryBuilder);
                    must.add(boolQueryBuilder);
                } else {
                    must.add(manageBoolQueryBuilder);
                }
            }
            /*else if (Objects.nonNull(query.getOrgId())) {
                // 没有配置组织架构
                ResponseDTO<OrganizeDRO> organDROResponseDTO = organizeListRemoteService.getByKey(query.getOrgId());
                OrganizeDRO organDRO = organDROResponseDTO.getData();
                if (Objects.nonNull(organDRO) && Objects.nonNull(organDRO.getLevel())) {
                    if (Objects.equals(organDRO.getLevel(), GlobalConsts.LEVEL_1)) {
                        must.add(QueryBuilders.termsQuery("orgOneId", Lists.newArrayList(query.getOrgId())));
                    } else if (Objects.equals(organDRO.getLevel(), GlobalConsts.LEVEL_2)) {
                        must.add(QueryBuilders.termsQuery("orgTwoId", Lists.newArrayList(query.getOrgId())));
                    } else if (Objects.equals(organDRO.getLevel(), GlobalConsts.LEVEL_3)) {
                        must.add(QueryBuilders.termsQuery("orgThreeId", Lists.newArrayList(query.getOrgId())));
                    }
                }
            }*/
        }

        // 城市
        boolean permitCity = Objects.equals(query.getPermitCity(), GlobalConsts.YES);
        if (permitCity) {
            SpermitDTO<DpermitLitDO> areaSpermitDTO = staffPermitRemoteService.listDpermitByStaffId(staffId, DpermitConsts.TYPE_AREA, true);
            if (CollectionUtils.isNotEmpty(areaSpermitDTO.getItems())) {

                // 按照城市查询
                if (Objects.equals(areaSpermitDTO.getLevel(), GlobalConsts.LEVEL_2)) {
                    must.add(QueryBuilders.termsQuery("provinceId", areaSpermitDTO.getItems()));
                } else if (Objects.equals(areaSpermitDTO.getLevel(), GlobalConsts.LEVEL_3)) {
                    must.add(QueryBuilders.termsQuery("cityId", areaSpermitDTO.getItems()));
                } else if (Objects.equals(areaSpermitDTO.getLevel(), GlobalConsts.LEVEL_4)) {
                    must.add(QueryBuilders.termsQuery("countyId", areaSpermitDTO.getItems()));
                }
            }
        }

        // 渠道
        boolean permitChannel = Objects.equals(query.getPermitChannel(), GlobalConsts.YES);
        if (permitChannel) {
            SpermitDTO<Integer> channelSpermitDTO = staffPermitRemoteService.listDpermitByStaffId(staffId, DpermitConsts.TYPE_COOPERATION, true);
            if (CollectionUtils.isNotEmpty(channelSpermitDTO.getItems())) {
                if (Objects.equals(channelSpermitDTO.getLevel(), GlobalConsts.LEVEL_1)) {
                    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                    boolQueryBuilder.should(QueryBuilders.termsQuery("channelOneId", channelSpermitDTO.getItems()));
                    boolQueryBuilder.should(QueryBuilders.termsQuery("sourceChannelOneId", channelSpermitDTO.getItems()));
                    must.add(boolQueryBuilder);
                } else if (Objects.equals(channelSpermitDTO.getLevel(), GlobalConsts.LEVEL_2)) {
                    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                    boolQueryBuilder.should(QueryBuilders.termsQuery("channelTwoId", channelSpermitDTO.getItems()));
                    boolQueryBuilder.should(QueryBuilders.termsQuery("sourceChannelTwoId", channelSpermitDTO.getItems()));
                    must.add(boolQueryBuilder);
                } else if (Objects.equals(channelSpermitDTO.getLevel(), GlobalConsts.LEVEL_3)) {
                    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                    boolQueryBuilder.should(QueryBuilders.termsQuery("channelId", channelSpermitDTO.getItems()));
                    boolQueryBuilder.should(QueryBuilders.termsQuery("sourceChannelId", channelSpermitDTO.getItems()));
                    must.add(boolQueryBuilder);
                }
            }
        }

        // 查询产品组相关权限
        if (!isPartQuery) {
            boolean permitProduct = Objects.equals(query.getPermitProduct(), GlobalConsts.YES);
            if (permitProduct) {
                SpermitDTO<Integer> productSpermitDTO = staffPermitRemoteService.listDpermitByStaffId(staffId, DpermitConsts.TYPE_PRODUCT, true);
                if (CollectionUtils.isNotEmpty(productSpermitDTO.getItems())) {
                    // 没有产品组、业务的数据的数据也要查询
                    productSpermitDTO.getItems().add(GlobalConsts.NONE);

                    if (Objects.equals(productSpermitDTO.getLevel(), GlobalConsts.LEVEL_1)) {
                        must.add(QueryBuilders.termsQuery("bizType", productSpermitDTO.getItems()));
                    } else if (Objects.equals(productSpermitDTO.getLevel(), GlobalConsts.LEVEL_2)) {
                        must.add(QueryBuilders.termsQuery("bizLine", productSpermitDTO.getItems()));
                    } else if (Objects.equals(productSpermitDTO.getLevel(), GlobalConsts.LEVEL_3)) {
                        must.add(QueryBuilders.termsQuery("servProductGroupId", productSpermitDTO.getItems()));
                    }
                }
            }
        }
    }

    /**
     * 获取 agg json数据
     *
     * @param nativeSearchQuery
     * @return
     */
    protected String getAggJson(NativeSearchQuery nativeSearchQuery) {
        if (nativeSearchQuery.getAggregations() == null) {
            return null;
        }
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
            builder.startObject();
            for (AbstractAggregationBuilder subAgg : nativeSearchQuery.getAggregations()) {
                subAgg.toXContent(builder, ToXContent.EMPTY_PARAMS);
            }
            builder.endObject();
            return builder.toString();

        } catch (IOException e) {
            logger.debug("Error parsing aggs");
            return null;
        }
    }

}
